package com.dwy2002.pojo.po.order;

import com.dwy2002.pojo.po.base.BaseEntity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 订单状态变更日志表实体类
 *
 * @author 杜伟毅
 * @version 1.0
 * @since 2025/03/06
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class OrderStatusLogs extends BaseEntity {
    /**
     * 关联订单ID
     */
    private String orderId;
    /**
     * 原状态
     */
    private Integer oldStatus;
    /**
     * 新状态
     */
    private Integer newStatus;
    /**
     * 操作人类型：1-系统 2-管理员 3-用户
     */
    private Integer operatorType;
    /**
     * 操作人ID
     */
    private String operatorId;
    /**
     * 状态变更说明
     */
    private String remark;
    /**
     * 逻辑删除
     */
    private Integer deleted;
    /**
     * 创建时间
     * <p>
     * 数据库默认值：创建的当前时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8", shape = JsonFormat.Shape.STRING)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)        // 反序列化
    @JsonSerialize(using = LocalDateTimeSerializer.class)        // 序列化
    private LocalDateTime createdAt;

    @Getter
    public enum OperatorTypeEnum {
        SYSTEM(1, "系统自动操作"),
        ADMIN(2, "后台管理员"),
        USER(3, "用户");

        // 带缓存校验（高频调用优化）
        private static final Set<Integer> CODE_SET =
                Arrays.stream(values()).map(OperatorTypeEnum::getCode)
                        .collect(Collectors.toSet());
        private final int code;
        private final String description;

        OperatorTypeEnum(int code, String description) {
            this.code = code;
            this.description = description;
        }

        // 通用校验方法
        public static boolean isValid(int value) {
            return Arrays.stream(values())
                    .anyMatch(e -> e.code == value);
        }

        public static boolean isValidOptimized(int value) {
            return CODE_SET.contains(value);
        }

        // 获取枚举实例
        public static Optional<OperatorTypeEnum> of(int code) {
            return Arrays.stream(values())
                    .filter(e -> e.code == code)
                    .findFirst();
        }
    }

}
